import React, { useCallback, useEffect, useState } from "react";
import {
  ActivityIndicator,
  Alert,
  FlatList,
  Text,
  View,
  TouchableHighlight,
  Animated,
  BackHandler,
  RefreshControl,
} from "react-native";
import {
  deleteBatchDevice,
  deleteDevice,
  getDeviceInfos,
} from "@/services/api/device";
import { DeviceLoginInfo } from "@/types/device";
import {
  convertDateStringToBeijingTime,
  convertToTodayTime,
} from "@/utils/time-utils";
import * as Device from "expo-device";
import { MaterialIcons } from "@expo/vector-icons";
import styles from "./device.style";
import { Stack } from "expo-router";
import { useTheme } from "@/contexts/ThemeContext";
import { getHeaderStyle } from "@/styles/header.style";
import Swipeable from "@/components/Global/Swipeable";
import { SharedValue, useAnimatedStyle } from "react-native-reanimated";
import { RectButton } from "react-native-gesture-handler";
import { getDeviceTypeLabel } from "@/utils/device-utils";
import { ResponseCode } from "@/types/api-common";
import TokenManager from "@/utils/token-utils";
import * as Notifications from "expo-notifications";
import CurrentUserIdManger from "@/utils/user-utils";
import { CommonActions, useNavigation } from "@react-navigation/native";
import {useStompClient} from "@/hooks/stomp/stomp-service";

export default function DeviceSettings() {
  // 获取当前主题模式
  const { themeMode } = useTheme();
  // 获取基于当前主题的header样式
  const headerStyles = getHeaderStyle(themeMode);

  // 导航对象
  const navigation = useNavigation();

  // 断开stomp连接函数
  const {disconnect} = useStompClient()

  // 设备列表状态
  const [devices, setDevices] = useState<DeviceLoginInfo[]>([]);
  const [refreshing, setRefreshing] = useState(true);

  //启用多选模式
  const [enableMultipleSelect, setEnableMultipleSelect] = useState(false);
  const [selected, setSelected] = useState<string[]>([]);

  const handleSelect = (deviceId: string) => {
    setSelected((prev) =>
      prev.includes(deviceId)
        ? prev.filter((id) => id !== deviceId)
        : [...prev, deviceId]
    );
  };

  const onRefresh = useCallback(async () => {
    setRefreshing(true);
    await fetchDevices();
    setRefreshing(false);
  }, []);

  const fetchDevices = async () => {
    setRefreshing(true);
    try {
      const res = await getDeviceInfos();
      setDevices(res.data.data || []);
    } catch (e) {
      Alert.alert("获取设备失败");
    }
    setRefreshing(false);
  };

  const handleDelete = async (deviceId: string) => {
    Alert.alert("删除设备", "是否删除该设备？", [
      { text: "取消", style: "cancel" },
      {
        text: "删除",
        onPress: async () => {
          setRefreshing(true);
          const resp = await deleteDevice(deviceId);
          if (resp.data.code === ResponseCode.SUCCESS) {
            setDevices((prev) =>
              prev.filter((item) => item.deviceId !== deviceId)
            );
            if (enableMultipleSelect) {
              setSelected((prev) => prev.filter((id) => id !== deviceId));
            }
            //
            if (deviceId === Device.osInternalBuildId) {
              console.log("登出成功");
              await TokenManager.clearToken();
              // 断开stomp连接
              console.log("stomp断开连接");
              await CurrentUserIdManger.clearUserId()
              disconnect();
              // setWebSocketMissConnected(false);
              // 取消所有通知处理
              await Notifications.dismissAllNotificationsAsync();
              Alert.alert("提示", "当前设备已被下线，请重新登录。", [
                {
                  text: "确定",
                  onPress: () => {
                    navigation.dispatch(
                      CommonActions.reset({
                        index: 0,
                        routes: [{ name: "login" }],
                      })
                    );
                  },
                },
              ]);
            }
          }
          setRefreshing(false);
        },
      },
    ]);
  };

  const deleteSelectedDevices = async () => {
    if (selected.length === 0) {
      Alert.alert("提示", "请至少选择一个设备");
      return;
    }
    Alert.alert("批量下线", `确定要下线 ${selected.length} 个设备吗？`, [
      { text: "取消", style: "cancel" },
      {
        text: "下线",
        onPress: async () => {
          setRefreshing(true);
          const resp = await deleteBatchDevice(selected);
          if (resp.data.code === ResponseCode.SUCCESS) {
            setDevices((prev) =>
              prev.filter((item) => !selected.includes(item.deviceId))
            );
            if (selected.includes(Device.osInternalBuildId)) {
              Alert.alert("提示", "当前设备已被下线，请重新登录。", [
                {
                  text: "确定",
                  onPress: () => {
                    console.log("登出成功");
                    TokenManager.clearToken();
                    // 断开stomp连接
                    console.log("stomp断开连接");
                    disconnect();
                    CurrentUserIdManger.clearUserId()
                    //  setWebSocketMissConnected(false);
                    // 取消所有通知处理
                    Notifications.dismissAllNotificationsAsync();
                    navigation.dispatch(
                      CommonActions.reset({
                        index: 0,
                        routes: [{ name: "login" }],
                      })
                    );
                  },
                },
              ]);
            }
            setSelected([]);
            setEnableMultipleSelect(false);
          }
          setRefreshing(false);
        },
      },
    ]);
  };

  const handleBackPress = () => {
    if (enableMultipleSelect) {
      setEnableMultipleSelect(false);
      setSelected([]);
      return true; // 阻止默认行为
    }
    return false; // 允许默认行为
  };

  useEffect(() => {
    fetchDevices();
  }, []);

  useEffect(() => {
    const backHandler = BackHandler.addEventListener(
      "hardwareBackPress",
      handleBackPress
    );
    return () => backHandler.remove();
  }, [enableMultipleSelect]);

  if (refreshing) {
    return <ActivityIndicator style={{ marginTop: 100 }} />;
  }

  const renderRightActions = (dragX: SharedValue<number>, deviceId: string) => {
    const animatedStyle = useAnimatedStyle(() => {
      return {
        transform: [{ translateX: dragX.value + 50 }],
      };
    });

    return (
      <Animated.View style={[styles.rightActionContainer, animatedStyle]}>
        <RectButton
          style={styles.deleteButton}
          onPress={() => handleDelete(deviceId)}
        >
          <MaterialIcons name="delete" size={24} color="#fff" />
          <Text style={{ color: "#fff", marginTop: 2 }}>下线</Text>
        </RectButton>
      </Animated.View>
    );
  };

  return (
    <>
      <Stack.Screen
        options={{
          title: "设备管理",
          headerTitleAlign: headerStyles.headerTitleAlign as "left" | "center",
          headerStyle: headerStyles.headerStyle,
          headerBackVisible: !enableMultipleSelect,
          headerLeft: () =>
            enableMultipleSelect && (
              <TouchableHighlight
                onPressIn={() => {
                  setEnableMultipleSelect(false);
                  setSelected([]);
                }}
              >
                <Text style={styles.headerRightText}>取消</Text>
              </TouchableHighlight>
            ),
          headerRight: () => (
            <View>
              {enableMultipleSelect ? (
                <View style={styles.headerRightAction}>
                  <TouchableHighlight onPressIn={deleteSelectedDevices}>
                    <Text style={[styles.headerRightText, styles.offlineText]}>
                      下线
                    </Text>
                  </TouchableHighlight>
                </View>
              ) : (
                <TouchableHighlight
                  onPressIn={() => setEnableMultipleSelect(true)}
                >
                  <Text style={styles.headerRightText}>管理</Text>
                </TouchableHighlight>
              )}
            </View>
          ),
          headerTintColor: headerStyles.headerTintColor,
          headerTitleStyle: headerStyles.headerTitleStyle,
        }}
      />
      <View style={styles.container}>
        {/*<TouchableOpacity style={styles.clearButton} onPress={handleClear}>*/}
        {/*    <Text style={styles.clearText}>清空除本机外所有设备</Text>*/}
        {/*</TouchableOpacity>*/}

        <FlatList
          data={devices}
          keyExtractor={(item) => item.id.toString()}
          refreshControl={
            <RefreshControl refreshing={refreshing} onRefresh={onRefresh} />
          }
          renderItem={({ item }) => {
            const isCurrentDevice = Device.osInternalBuildId === item.deviceId;
            const content = (
              <TouchableHighlight
                underlayColor="#eee"
                onPress={() => {
                  if (enableMultipleSelect) handleSelect(item.deviceId);
                }}
                style={[
                  styles.deviceCard,
                  enableMultipleSelect &&
                    selected.includes(item.deviceId) && {
                      backgroundColor: "#e6f7ff",
                    },
                ]}
              >
                <View style={styles.deviceRow}>
                  {enableMultipleSelect && (
                    <View
                      style={{
                        width: 24,
                        height: 24,
                        borderRadius: 12,
                        borderWidth: 2,
                        borderColor: "#1890ff",
                        backgroundColor: selected.includes(item.deviceId)
                          ? "#1890ff"
                          : "#fff",
                        marginRight: 10,
                        alignItems: "center",
                        justifyContent: "center",
                      }}
                    >
                      {selected.includes(item.deviceId) && (
                        <MaterialIcons name="check" size={16} color="#fff" />
                      )}
                    </View>
                  )}
                  <MaterialIcons
                    name={item.deviceType === 3 ? "computer" : "smartphone"}
                    size={24}
                    color="#333"
                    style={{ marginRight: 10 }}
                  />
                  <View style={{ flex: 1 }}>
                    <Text style={styles.deviceName}>
                      <Text ellipsizeMode="tail">{item.deviceName}</Text>
                      {isCurrentDevice && (
                        <Text style={styles.currentTag}>（本机）</Text>
                      )}
                    </Text>
                    <Text style={styles.deviceType}>
                      {getDeviceTypeLabel(item.deviceType)}
                    </Text>
                    <Text style={styles.deviceTime}>
                      {convertToTodayTime(
                        convertDateStringToBeijingTime(item.updateTime)
                      )}{" "}
                      | {item.ipDescription}
                    </Text>
                  </View>
                </View>
              </TouchableHighlight>
            );

            return (
              <Swipeable
                renderRightActions={(dragX) =>
                  renderRightActions(dragX, item.deviceId)
                }
              >
                {content}
              </Swipeable>
            );
          }}
        />
      </View>
    </>
  );
}
